<template>
	<view class="fix-top-window">
		<!-- <button @click="onDemo"  > 火箭发射按钮</button> -->
		<view class="uni-header">
			<uni-stat-breadcrumb class="uni-stat-breadcrumb-on-phone" />
			<view class="uni-group">
				<view class="uni-sub-title hide-on-phone"></view>
			</view>
		</view>
		<view class="p-m">
			<view class="statis_grid list">
				<view class="grid_box animated-item  " v-for="(item,index) in chartsData">
					<view class="box_title">
						<text class="TelApp">
							{{item.title}}
						</text>
						<view class="icon" :style="`background:${item.background};`">
							<uni-icons :type="item.icon" size="30" :color="item.color"></uni-icons>
						</view>
					</view>
					<view class="box_body">
						<view class="number titleApp textApp2 ">
							{{floatNumber(item.dayNumber)}}
						</view>
						<view>
							<view>
								<text class="labelApp ">
									{{item.lable}} &nbsp;
								</text>
								<text class="titleApp textApp">
									{{floatNumber(item.number ) }}
								</text>
							</view>
							<view style="margin:10px 0 0 0">
								<text style="color:#f53b57">
									<text v-if="item.yesterday < item.dayNumber " style="color: #44bd32">
										<text class="labelApp">
											较昨日
										</text>
										{{(item.dayNumber - item.yesterday).toFixed(0)}}
										&nbsp;
										<text class="textApp2" style="font-size:18px;  text-shadow:-1px 8px 5px #44bd32;">
											↗
										</text>
									</text>
									<text v-else style="color:#f53b57 ">
										<text class="labelApp">
											较昨日
										</text>
										{{(item.dayNumber - item.yesterday).toFixed(0)}}
										<text class="textApp2" style="font-size:18px;  text-shadow:0px 8px 4px #f53b57;">
											↘
										</text>
									</text>
								</text>
							</view>

						</view>

					</view>
				</view>
			</view>
			<view class="qiun_grid">
				<view class="qiun">
					<qiun-data-charts type="area" :opts="areaopts" :chartData="chartDataArea" />
				</view>
			</view>
		</view>


		<!-- #ifndef H5 -->
		<fix-window />
		<!-- #endif -->
	</view>
</template>

<script>
	const PUSH = uniCloud.importObject("push", { customUI: true })
	import {
		deviceFeildsMap,
		userFeildsMap
	} from './fieldsMap.js'

	import {
		initOrder,
		initUser,
		initAreaBill
	} from "./init.js"
	import Util from "@/js_sdk/validator/util.js"
	import { areaPower  } from "@/js_sdk/manage-area/manage.js";
	const db = uniCloud.database()
	let startTime = Util.getDayTimestamps(0).startTime;
	let endTime = Util.getDayTimestamps(0).endTime;
	export default {
		data() {
			return {
				loading: true,
				chartsData: [],
				loading1: true,
				wherePageView: {
					"create_date.time_stamp": db.command.gt(startTime).and(db.command.lt(endTime))
				},
				// 分页
				total: 0, //  总条数
				skip: 0, // 开始查询位置
				limit: 10, // 单词查询条数
				currentPage: 1, // 当前页
				pageViewData: [],
				/*图表*/
				// 区域图表
				chartDataArea: {},
				areaopts: {
					color: ["#ea7ccc", "#73C0DE", "#FAC858", "#EE6666", "#73C0DE", "#3CA272", "#FC8452", "#9A60B4", "#ea7ccc"],
					padding: [15, 1, 0, 1],
					enableScroll: false,
					legend: {},
					xAxis: {  disableGrid: true  },
					yAxis: { gridType: "dash",  dashLength: 2 },
					extra: {
						area: {
							type: "curve",
							opacity: 0.8,
							addLine: true,
							width: 2,
							gradient: true,
							activeType: "hollow"
						}
					}
				},
			}
		},
		onReady() {
			let res = uni.getStorageSync("chart-data") || null;
			if (res && typeof res === 'object' && res.time > Date.now()) {
				setTimeout(() => {
					this.chartDataArea = JSON.parse(JSON.stringify(res.res));
				}, 500);
			} else {
				this.getServerData();
			}
			// this.getServerData();
		},
		onLoad() {
			this.initData()
		},
		methods: {
			onDemo() {
			},
			async getServerData() {
				const dbCmd = db.command;
				const $ = db.command.aggregate;
				const filed = "status,_id,pay_date"
				const categories = this.getRecentWeekDates();
				let orders = [];
				let deliveryPrice = [];
				let platformCommission = [];
				for (var i = 10; i > 0; i--) {
					const _7day1 = Util.getStartAndEndTimestamp(i).startTime
					const _7day2 = Util.getStartAndEndTimestamp(i - 1).startTime
					const order = await  db.collection('orders').aggregate()
					.lookup({
						from: 'shop',
						let: { shopId:"$shop_id",areaS:"05300103" },
						pipeline: $.pipeline()
						.match(dbCmd.expr(
							$.and([
								$.eq(['$_id', '$$shopId']),
							])
						))
						.done(),
						as: 'shopInfo'
					})
					.match({
						pay_date: dbCmd.gt(_7day1).and(dbCmd.lt(_7day2)),
						"status.value": dbCmd.gt(1).and(dbCmd.lt(9)),
						"shopInfo.area_all.value":dbCmd.in( areaPower() ) ,
					})
					.group({
					  _id: null,
					  count:$.sum(1),
					  deliveryPrice:$.sum("$delivery_price"),
					  platformCommission:$.sum("$platform_commission")
					}).end()
					if(order.result.data.length > 0){
						orders.push(order.result.data[0].count)
						deliveryPrice.push( (order.result.data[0].deliveryPrice / 100).toFixed(1) )
						platformCommission.push( (order.result.data[0].platformCommission / 100).toFixed(1) )
					}
				}
				let series = [
					{name: "订单量",data: orders},
					{name: "佣金收入",data: platformCommission},
					{name: "配送费",data: deliveryPrice}
				]
				let res = {
					categories,series
				};
				let store = {
					res,time: Date.now() + 1000 * 60 * 60 * 12
				}
				uni.setStorageSync("chart-data", store)
				this.chartDataArea = JSON.parse(JSON.stringify(res));
			},
			// 整数返回
			floatNumber(number) {
				return Util.formatNumber(number)
			},
			userHasPermission(admin = []) {
				return Util.userHasPermission(admin)
			},
			// 分页
			enventFneye(val) {
				this.skip = (val.current - 1) * 10
				this.getPageViewData()
			},
			// 初始化数据
			initData() {
				// initOrder().then(orderData => {
				// 	this.chartsData.push(orderData)
				// })
				// initUser().then(userData => {
				// 	this.chartsData.push(userData)
				// })
				initAreaBill().then(Data => {
					this.chartsData.push(Data.orderCount)
					this.chartsData.push(Data.platform)
					this.chartsData.push(Data.delivery)
				})
			},
			getRecentWeekDates() {
				let today = new Date(); // 获取当前日期
				let weekDates = []; // 存储最近一周的日期

				for (let i = 10; i >= 1; i--) {
					let date = new Date(today); // 克隆当前日期对象
					date.setDate(today.getDate() - i); // 减去 i 天
					let month = String(date.getMonth() + 1).padStart(2, '0'); // 获取月份，并补零
					let day = String(date.getDate()).padStart(2, '0'); // 获取日期，并补零
					let formattedDate = `${month}-${day}`; // 格式化日期为 YYYY-MM-DD
					weekDates.push(formattedDate); // 将日期添加到数组
				}
				return weekDates;
			},
		}

	}
</script>
<style lang="scss" scoped>
	.qiun_grid {
		display: grid;
		grid-template-columns:  1fr 1fr; 
		column-gap: 30px;
		row-gap: 20px;
		margin: 30px 0;
		.qiun {
			padding: 20px;
			box-shadow: 0 1px 20px 0 #d8e2e2;
		}
	}

	.charts-box {
		width: 450px;
		height:400px;
	}

	.animated-item {
		opacity: 0;
		transform: translateX(100px);
		animation: fadeInLeft 1s ease forwards;
	}

	@keyframes fadeInLeft {
		to {
			opacity: 1;
			transform: translateX(0);
		}
	}

	.statis_grid {
		display: grid;
		grid-template-columns: repeat(auto-fill, minmax(305px, 1fr));
		column-gap: 30px;
		row-gap: 20px;
		.grid_box {
			height: 200px;
			border-radius: 5px;
			box-shadow: 0 1px 20px 0 #d8e2e2;
			padding: 20px 50px;

			.box_title {
				display: flex;
				justify-content: space-between;
				align-items: center;

				.icon {
					width: 50px;
					height: 50px;
					display: flex;
					border-radius: 50%;
					justify-content: center;
					align-items: center;
				}
			}

			.box_body {
				.number {
					font-size: 45px;
					font-weight: 900;
					line-height: 60px;
				}
			}
		}
	}

	.uni-stat-card-header {
		display: flex;
		justify-content: space-between;
		color: #555;
		font-size: 14px;
		font-weight: 600;
		padding: 10px 10px;
		margin-bottom: 15px;
	}

	.uni-table-scroll {
		min-height: auto;
	}

	.link-btn-color {
		color: #2979FF;
		cursor: pointer;
	}

	.uni-stat--x {
		padding: 20px;
	}

	.uni-stat-text {
		color: #606266;
	}

	.mt10 {
		margin-top: 10px;
	}

	.uni-radio-cell {
		margin: 0 10px;
	}

	.uni-stat-tooltip-s {
		width: 400px;
		white-space: normal;
	}

	.uni-a {
		cursor: pointer;
		text-decoration: underline;
		color: #555;
		font-size: 14px;
	}
</style>